package com.czk.security.controller;

import com.czk.security.model.AuthenticationRequest;
import com.czk.security.model.UserDto;
import com.czk.security.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/3/18 22:57
 */
@RestController
public class LoginController {
    @Autowired
    private AuthenticationService authenticationService;

    @RequestMapping(value = "/login", produces = "text/plain;charset=utf-8")
    public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
        UserDto authentication = authenticationService.authentication(authenticationRequest);
        // 存入session
        session.setAttribute(UserDto.SESSION_USER_KEY, authentication);
        return authentication.getUsername() + "登陆成功";
    }

    /**
     * session验证
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=utf-8"})
    public String rl(HttpSession session) {
        Object attribute = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (attribute == null) {
            return "匿名访问";
        } else {
            UserDto userDto = (UserDto) attribute;
            return userDto.getUsername() + "登陆了";
        }
    }

    /**
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=utf-8"})
    public String r2(HttpSession session) {
        Object attribute = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (attribute == null) {
            return "匿名访问";
        } else {
            UserDto userDto = (UserDto) attribute;
            return userDto.getUsername() + "登陆了";
        }
    }

    /**
     * 退出，清除session
     *
     * @param session
     * @return
     */
    @GetMapping("/loginout")
    public String loginout(HttpSession session) {
        session.invalidate();
        return "退出成功";
    }
}
